import { Map, View, Collection } from "ol";
import * as proj from 'ol/proj';
import * as geom from 'ol/geom';

import { Group, Tile ,Vector} from "ol/layer"
import * as control from 'ol/control';
// import OLCesium from 'olcs/OLCesium.js';
import * as tilegrid from 'ol/tilegrid';
import TGWMTS from 'ol/tilegrid/WMTS';
import Feature  from 'ol/Feature';
import { WMTS ,XYZ,Vector as VectorSource} from 'ol/source';
import * as extent from 'ol/extent';
import gisdata from "@/plugins/gisdata";
import {
    Circle as CircleStyle,
    Fill,
    Icon,
    Stroke,
    Style,
} from 'ol/style';
function SworldMap(options) {
    //二维地图初始化地图
    this._base2DLayer = new Group({
        layers: []
    });
    this._base2DLayer.name = '地图底图图层组';
    //底图标签
    this._base2DLayer.isBaseLayer = true;
    //默认为三维地图
    this.isD3Map = false;
    this._d2map=null;
}

/**
 * 获取瓦片源数据对象
 * @param {object} urlModel 瓦片参数
 * @returns
 */
SworldMap.prototype.getSource = function (urlModel) {
    var source = null;
    var projection = proj.get('EPSG:3857');
    if (urlModel.project) {
        projection = proj.get(urlModel.project);
    }

    //切片方案,有配置最大或最小比例层级时，定制对应的切片方案，只显示那几级
    var tileGrid = (urlModel.maxZoom !== undefined || urlModel.minZoom !== undefined) ?
        tilegrid.createXYZ({
            extent: projection.getExtent(),
            maxZoom: urlModel.maxZoom,
            minZoom: urlModel.minZoom,
            tileSize: urlModel.tileSize
        }) : undefined;

    switch (urlModel.type) {
        case "WMTS":
            var projectionExtent = projection.getExtent();
            var size = extent.getWidth(projectionExtent) / 256;
            var level_vol = urlModel.zoomVolatility || 0;//级别上下浮动值
            var gridName = urlModel.gridName || '';//geoserver gridName
            var resolutions = new Array(14);
            var matrixIds = new Array(14);
            for (var z = 0; z < 18; ++z) {
                resolutions[z] = size / Math.pow(2, z);
                matrixIds[z] = gridName + (z + level_vol);
            }
            source = new WMTS({
                url: urlModel.url,
                layer: urlModel.layer,
                matrixSet: urlModel.matrixSet,
                format: urlModel.format,
                projection: urlModel.projection || projection,
                tileGrid: urlModel.tileGrid || new TGWMTS({
                    origin: extent.getTopLeft(projectionExtent),
                    resolutions: resolutions,
                    matrixIds: matrixIds
                }),
                style: urlModel.style,
                wrapX: true,
                crossOrigin: 'anonymous',
                tileLoadFunction: urlModel.tileLoadFunction,
                dimensions: {
                    'tk': urlModel.tk
                }
            });
            break;
    }
    return source;
}

/**
 * 加载地图瓦片图层
 */
SworldMap.prototype._load2DBaseLayers = function () {

    // var _baseMap2DUrls = [{
    //     name: "天地图WGS84卫星影像图",
    //     url: osm_street_url,
    //     layer: 'img',
    //     matrixSet: 'c',
    //     format: 'tiles',
    //     style: 'default',
    //     maxZoom: this._mapMaxZoom,
    //     type: 'WMTS',
    //     project: "EPSG:4326",
    //     tk: '您的天地图Token'
    // }
    // , {
    //     name: "天地图WGS84卫星影像标签",
    //     url: 'http://t{0-7}.tianditu.gov.cn/cia_c/wmts?',
    //     layer: 'cia',
    //     matrixSet: 'c',
    //     format: 'tiles',
    //     style: 'default',
    //     maxZoom: this._labelMaxZoom,
    //     type: 'WMTS',
    //     project: "EPSG:4326",
    //     tk: '您的天地图Token'
    // }
    // ];
    //清空已有底图
    this._base2DLayer.getLayers().clear();
    //添加新底图
    var layers = [];
    // for (var i = 0; i < _baseMap2DUrls.length; i++) {
    //     var dataSource = this.getSource(_baseMap2DUrls[i]);
    //     var tileGrid = dataSource.getTileGrid();
    //     var layer = new Tile({
    //         source: dataSource,
    //         maxZoom: 30
    //     });
    //     layer.name = _baseMap2DUrls[i].name ? _baseMap2DUrls[i].name : "";
    //     layers.push(layer);
    // }
    // https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/14/6780/13043

        let  osm_token = "tI2QmeUdvQ6zTABrLQszB5EYdZbUAfKzKTdAvPpPw2b9xBd9vFPrNb99QyCEJVzq";
// const osm_street_url = "https://tile.jawg.io/jawg-streets/{z}/{x}/{y}.png?access-token="+osm_token;
//     let osm_street_url = "https://tile.jawg.io/light/{z}/{x}/{y}.png?access-token="+osm_token;
    let osm_street_url = "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}";

    let gaodeLayer = new Tile({
        source: new XYZ({
            //url: "https://webrd0{s}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=040&size=1&scale=1&ltype=7",
            //url : 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=10',
            // url : 'http://webst03.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&style=7',
            //  url: "http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=2&scale=1&style=8",
            url:osm_street_url,
            // http://webst03.is.autonavi.com/appmaptile?x=214038&y=114227&z=18&style=7,
            crossOrigin: "anonymous",
        }),
    });
    layers.push(gaodeLayer)
    this._base2DLayer.setLayers(new Collection(layers));
}

SworldMap.prototype.initMap = function () {
    this._load2DBaseLayers();
    //初始化二维地图
    this._d2map = new Map({
        controls: control.defaults({
            zoom: false,
            attribution: false,
            rotate: false
        }),
        layers: [this._base2DLayer],
        target: "map",
        view: new View({
            center: proj.transform([106.45, 29.56], 'EPSG:4326', 'EPSG:4326'),
            zoom: 12,
            projection: 'EPSG:4326',
            minZoom: 0,
            maxZoom: 18
        }),
        logo: false,
    });
    this.addLine(gisdata[0].features)
    // var map3dContainer = null;
    //附加三维地图（负责三维地图创建、同步）
    // this._d3map = new OLCesium({
    //     map: this._d2map,
    //     terrainExaggeration: 0,
    //     target: map3dContainer
    // });
}

/**
 * 二三维切换
 * @date 2023-03-30
 * @returns {any}
 */
SworldMap.prototype.switchMap = function () {
    let b = (this.isD3Map) ? false : true;
    this._d3map.setEnabled(b);
}
SworldMap.prototype.addLine=function (fs){
    let lsource = new VectorSource(); //新建一个source/vector 数据源
    let psource = new VectorSource();
    for(var i=0;i<fs.length;i++){
        if(fs[i].geometry.type=='LineString'){
            var coords=fs[i].geometry.coordinates;
            var points=[];
            for(var j=0;j<coords.length;j++){

                points.push(proj.transform([coords[j][0], coords[j][1]], 'EPSG:4326', 'EPSG:4326'));
            }
            let f = new Feature({
                name: fs[i].properties.name,
                type: 'route',
                // 这里是一个数组模式
                geometry: new geom.LineString(points),

            });
            f.set('name',fs[i].properties.name);
            lsource.addFeature(f);
        }else if(fs[i].geometry.type=='Point'){
            let coords=fs[i].geometry.coordinates;
            let  geoMarker = new Feature({
                type: 'geoMarker',
                geometry: new geom.Point(proj.transform([coords[0], coords[1]], 'EPSG:4326', 'EPSG:4326')),
            });
            psource.addFeature(geoMarker);
        }
    }
    console.log('style')

    //source.addFeature(feature); //数据源设置上面的feture矢量数据 （3）
    let llayer = new Vector({
        style: {
            'stroke-color': 'rgba(0, 255, 255, 0.7)',
            'stroke-width': 6,
        }

        //     function (feature) {
        //     console.log('style')
        //     // console.log(feature.get('name'),'getname');
        //     if(feature.get('name')){
        //         // let linename=feature.get('name');
        //
        //         return new Style({
        //             stroke: new Stroke({
        //                 width: 8,
        //                 color: 'red',
        //             }),
        //         })
        //     }else{
        //         return new Style({
        //             stroke: new Stroke({
        //                 width: 8,
        //                 color: 'red',
        //             }),
        //         })
        //     }
        // }
    });
    let player = new Vector({
        style: function () {

            return  new Style({
                image: new CircleStyle({
                    radius: 3,
                    fill: new Fill({color: 'white'}),
                    stroke: new Stroke({
                        color: 'yellow',
                        width: 1,
                    }),
                }),
            });

        }
    });
    //新建一个地图的layer/vector图层
    llayer.setSource(lsource); //layer设置一个数据源 （2）
     player.setSource(psource);
     this._d2map .addLayer(llayer); //地图添加layer图层 （1） 这里就是新建地图的那个map添加图层
     this._d2map .addLayer(player);
}
export default SworldMap;
